﻿// MIT License
//
// Copyright (c) 2021-present zuohuaijun, Daming Co.,Ltd and Contributors
//
// 电话/微信：18020030720 QQ群1：87333204 QQ群2：252381476

using Admin.NET.Application.Const;
using Admin.Net.InformationPlatform.Entity;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Mvc;
using Nest;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Furion.FriendlyException;
using Admin.Net.InformationPlatform.Entity.Order;
using Admin.Net.InformationPlatform.Service.SRM.Dto;
using Admin.Net.InformationPlatform.Service.Order.Dto;
using Admin.NET.Core;
using Admin.NET.Core.Service;
using iTextSharp.text.pdf.parser.clipper;
using Microsoft.Office.Interop.Word;
using System.Collections;
using Admin.NET.Core.Entity;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Core;
using Aliyun.Acs.Dysmsapi.Model.V20170525;
using Microsoft.AspNetCore.Authorization;
using Admin.Net.InformationPlatform.Util;
using Admin.Net.InformationPlatform.Entity.Product;

namespace Admin.Net.InformationPlatform.Service.Order
{
    /// <summary>
    /// 下单平台
    /// </summary>
    [ApiDescriptionSettings(groups: "Order", Name = "客户报备", Tag = "客户报备", Order = 200)]

    public class CustomerReportService : IDynamicApiController, ITransient
    {
        private readonly SysUserRoleService _sysUserRoleService;
        /// <summary>
        /// 单例数据链接
        /// </summary>
        ISqlSugarClient db;
        /// <summary>
        /// T100数据库
        /// </summary>
        private SqlSugarProvider _T100Db;
        private SqlSugarProvider _SjDb;
        private SqlSugarProvider _plm;
        private SqlSugarProvider _Dilon;
        private SqlSugarProvider _Ecology;
        public string Salesman = "14478138094149";//业务员角色
        public string CityManager = "14555212310213";//城市经理角色



        /// <summary>
        /// 用户信息
        /// </summary>
        TokenUser _User;
        /// <summary>
        /// 成品仓库管理模块
        /// </summary>
        /// <param name="db"></param>
        public CustomerReportService(ISqlSugarClient db, SysUserRoleService sysUserRoleService)
        {
            this.db = db;
            this._T100Db = this.db.AsTenant().GetConnection(T100Const.ConfigId);
            this._SjDb = this.db.AsTenant().GetConnection(SJDB.ConfigId);
            this._plm = this.db.AsTenant().GetConnection(PLM.ConfigId);
            this._Dilon = this.db.AsTenant().GetConnection(Dilon.ConfigId);
            this._Ecology = this.db.AsTenant().GetConnection(Ecology.ConfigId);
            // 获取 `Jwt` 存储的信息 企业编号与据点信息
            _User = Util.SjCommonUtil.GetT100UserTokenInfo(_T100Db, _Dilon);
            _sysUserRoleService = sysUserRoleService;

        }
        /// <summary>
        /// 判断客户是否存在
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/Order/IsCustomerExist")]
        public async Task<bool> IsCustomerExist(IsCustomerExist input)
        {
            if (string.IsNullOrEmpty(input.TAXID) || string.IsNullOrEmpty(input.PRODUCTSLINE))
            {
                throw Oops.Oh($"输入税号和产品线不能为空！");
            }
            //判断单据存在
            int cnt = await _SjDb.Queryable<FilingClient>()
                .Where(a => a.TAXID == input.TAXID)//客户税号
                .Where(a => a.PRODUCTSLINE == input.PRODUCTSLINE)//产品线
                .Select(a => a.ID)
                .CountAsync();
            if (cnt == 0)
                return true;
            else
                return false;

        }
        /// <summary>
        /// 增加客户报备记录
        /// </summary>
        /// <returns></returns>
        [HttpPost("/Order/AddCustomerReport")]
        public async Task<string> AddCustomerReport(FilingClient input)
        {
            var ENDTIME = Convert.ToDateTime(Convert.ToDateTime(input.ENDTIME).ToString("yyyy-MM-dd"));//开发结束时间
            var TODAY = Convert.ToDateTime(Convert.ToDateTime(DateTime.Now).ToString("yyyy-MM-dd"));//开发结束时间
            if (ENDTIME < TODAY)
            {
                throw Oops.Oh($"开发时间不能小于今天！");
            }
            int state = 1;//审核中
            TimeSpan duration = ENDTIME.Subtract(TODAY);
            int days = duration.Days;//时间差
            if (days <= 3)
            {
                state = 5;//即将失效
            }

            var details = new FilingClient
            {
                ID = Guid.NewGuid().ToString("N"),
                CUSTOMERNAME = input.CUSTOMERNAME,
                TAXID = input.TAXID,
                PRODUCTSLINE = input.PRODUCTSLINE,
                INFLUENCE = input.INFLUENCE,
                CONTACT = input.CONTACT,
                PHONENUMBER = input.PHONENUMBER,
                POSTS = input.POSTS,
                ENDTIME = input.ENDTIME,
                BUSINESSSCOPE = input.BUSINESSSCOPE,
                SJPRODUCTS = input.SJPRODUCTS,
                PURCHASEAMOUNT = Convert.ToDouble(input.PURCHASEAMOUNT),
                OPPONENTAMOUNT = Convert.ToDouble(input.OPPONENTAMOUNT),
                BACKGROUND = input.BACKGROUND,
                DEVELOPMENTREASON = input.DEVELOPMENTREASON,
                PURCHASEDESCRIPTION = input.PURCHASEDESCRIPTION,
                PURCHASEDATA = input.PURCHASEDATA,
                STATE = state,
                CREATETIME = DateTime.Now,
                BBR = _User.RealName,
                BBRPHONE = _User.Phone,
                BBREMAIL = _User.Email,
                BBRID = _User.UserId



            };

            #region 插入事务
            try
            {
                //开启事务
                _SjDb.Ado.BeginTran();
                int cnt = await _SjDb.Insertable<FilingClient>(details).ExecuteCommandAsync();

                if (cnt == 0)
                {
                    throw Oops.Oh($"新建任务失败！");
                }
                //提交事务
                _SjDb.Ado.CommitTran();
                //提交OA
                CustomerOAService.CreateOAAsync(input);
                return "插入成功";
            }
            catch (Exception e)
            {
                //回滚事务
                _SjDb.Ado.RollbackTran();
                throw Oops.Oh($"异常：{e.Message}");
            }
            #endregion

        }
        /// <summary>
        ///  获取客户报备列表-分页
        /// </summary>
        /// <returns></returns>
        [HttpPost("/Order/GetCustomerPagedList")]
        public async Task<SqlSugarPagedList<FilingClient>> GetCustomerPagedList(CustomerInput input)
        {
            // 角色信息
            var LoginRoles = _Dilon.Queryable<SysUserRole>()
                 .LeftJoin<SysUser>((r, u) => (r.UserId == u.Id))
                       .Where((r, u) => r.UserId.ToString() == _User.ID)
                      .Select((r, u) => new SalesmanRole
                      {
                          USERID = u.Account,
                          USERNAME = u.RealName,
                          ROLEID = r.RoleId.ToString()
                      }).ToList();
            int role1 = LoginRoles.Where(u => u.ROLEID == CityManager).Count();//判断是否拥有城市经理角色
            int role = LoginRoles.Where(u => u.ROLEID == Salesman).Count();//判断是否拥有业务员角色
            //报备人合集
            List<string> bbrlist = new List<string>();

            if (role1 > 0)
            {
                //根据当前登录人，查询出所有下级数据
                var data = _Ecology.Ado.SqlQuery<string>($@"
                  WITH RecursiveCTE AS (
    SELECT loginid,ID, managerid
    FROM HrmResource
    WHERE ID = (SELECT id from HrmResource where loginid ='007637') 
    UNION ALL
    SELECT yt.loginid,yt.ID, yt.managerid
    FROM HrmResource yt
    JOIN RecursiveCTE cte ON yt.managerid = cte.ID
)
SELECT loginid
FROM RecursiveCTE
            ").ToList();
                //查询城市经理下的业务员信息
                var values = _Dilon.Queryable<SysUserRole>()
                .LeftJoin<SysUser>((r, u) => (r.UserId == u.Id))
                .Where((r, u) => r.RoleId.ToString() == Salesman)
                .Where((r, u) => u.OrgId.ToString() == _User.OrgId)
                 .Select((r, u) => new SalesmanRoles
                 {
                     BBR = u.Account,
                 }).ToList();
                
                 for(int i = 0; i < data.Count; i++)
                {
                    bbrlist.Add(data[i]);
                }
            }

            var output = await _SjDb.Queryable<FilingClient>()
    .WhereIF(!string.IsNullOrEmpty(input.CUSTOMERNAME), (l) => (l.CUSTOMERNAME.Contains(input.CUSTOMERNAME)))//客户名称
    .WhereIF(!string.IsNullOrEmpty(input.INFLUENCE), (l) => (l.INFLUENCE.Contains(input.INFLUENCE)))//所属行业及影响力
    .WhereIF(input.STATE > 0, (l) => l.STATE == input.STATE)//报备客户状态
    .WhereIF(role == 1, (l) => l.BBRID == _User.UserId)//业务员只能看自己的数据
     .WhereIF(role1==1, (l) => bbrlist.Contains(l.BBRID))//城市经理可以看到自己名下业务员数据
    .OrderBy(l => l.BBR, OrderByType.Desc) //报备人
    .OrderBy(l => l.CREATETIME, OrderByType.Desc) //报备日期排序
    .Select(l => new FilingClient
    {
        ID = l.ID,
        CUSTOMERNAME = l.CUSTOMERNAME,
        TAXID = l.TAXID,
        PRODUCTSLINE = l.PRODUCTSLINE,
        INFLUENCE = l.INFLUENCE,
        CONTACT = l.CONTACT,
        PHONENUMBER = l.PHONENUMBER,
        POSTS = l.POSTS,
        ENDTIME = l.ENDTIME,
        BUSINESSSCOPE = l.BUSINESSSCOPE,
        SJPRODUCTS = l.SJPRODUCTS,
        PURCHASEAMOUNT = Convert.ToDouble(l.PURCHASEAMOUNT),
        OPPONENTAMOUNT = Convert.ToDouble(l.OPPONENTAMOUNT),
        BACKGROUND = l.BACKGROUND,
        DEVELOPMENTREASON = l.DEVELOPMENTREASON,
        PURCHASEDESCRIPTION = l.PURCHASEDESCRIPTION,
        PURCHASEDATA = l.PURCHASEDATA,
        STATE = l.STATE,
        CREATETIME = l.CREATETIME,
        BBR = l.BBR,
        BBRID = l.BBRID,

    }).ToPagedListAsync(input.Page, input.PageSize);
            return output;
        }

        /// <summary>
        ///  根据id获取客户报备记录
        /// </summary>
        /// <returns></returns>
        [HttpPost("/Order/GetCustomerById")]
        public async Task<List<FilingClient>> GetCustomerById(CustomerById input)
        {

            var output = await _SjDb.Queryable<FilingClient>()
    .WhereIF(!string.IsNullOrEmpty(input.ID), (l) => (l.ID == input.ID))//客户名称
    .Select(l => new FilingClient
    {
        ID = l.ID,
        CUSTOMERNAME = l.CUSTOMERNAME,
        TAXID = l.TAXID,
        PRODUCTSLINE = l.PRODUCTSLINE,
        INFLUENCE = l.INFLUENCE,
        CONTACT = l.CONTACT,
        PHONENUMBER = l.PHONENUMBER,
        POSTS = l.POSTS,
        ENDTIME = l.ENDTIME,
        BUSINESSSCOPE = l.BUSINESSSCOPE,
        SJPRODUCTS = l.SJPRODUCTS,
        PURCHASEAMOUNT = Convert.ToDouble(l.PURCHASEAMOUNT),
        OPPONENTAMOUNT = Convert.ToDouble(l.OPPONENTAMOUNT),
        BACKGROUND = l.BACKGROUND,
        DEVELOPMENTREASON = l.DEVELOPMENTREASON,
        PURCHASEDESCRIPTION = l.PURCHASEDESCRIPTION,
        PURCHASEDATA = l.PURCHASEDATA,
        STATE = l.STATE,
        CREATETIME = l.CREATETIME,
        BBR = l.BBR

    }).ToListAsync();
            return output;
        }

        /// <summary>
        /// 报备客户更改
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/Order/UpdateCustomer")]
        public async Task<string> UpdateComputerRoom(FilingClient input)
        {
            if ((new int[] { 2, 6 }).Contains(input.STATE))
            {
                var ENDTIME = Convert.ToDateTime(Convert.ToDateTime(input.ENDTIME).ToString("yyyy-MM-dd"));//开发结束时间
                var TODAY = Convert.ToDateTime(Convert.ToDateTime(DateTime.Now).ToString("yyyy-MM-dd"));//开发结束时间
                if (ENDTIME < TODAY)
                {
                    throw Oops.Oh($"开发时间不能小于今天！");
                }
                int state = 1;//审核中
                TimeSpan duration = ENDTIME.Subtract(TODAY);
                int days = duration.Days;//时间差
                if (days <= 3)
                {
                    state = 5;//即将失效
                }
                //判断单据存在
                int cnt = await _SjDb.Queryable<FilingClient>()
                    .Where(a => a.ID == input.ID)
                    .Select(a => a.ID)
                    .CountAsync();


                if (cnt == 0)
                {
                    throw Oops.Oh("任务不存在，驳回！");
                }
                else
                {
                    //提交
                    try
                    {
                        _SjDb.Ado.BeginTran();
                        int count = await _SjDb.Updateable<FilingClient>()
                            .SetColumns(a => a.CUSTOMERNAME == input.CUSTOMERNAME)
                            .SetColumns(a => a.TAXID == input.TAXID)
                            .SetColumns(a => a.PRODUCTSLINE == input.PRODUCTSLINE)
                            .SetColumns(a => a.INFLUENCE == input.INFLUENCE)
                            .SetColumns(a => a.CONTACT == input.CONTACT)
                            .SetColumns(a => a.PHONENUMBER == input.PHONENUMBER)
                            .SetColumns(a => a.POSTS == input.POSTS)
                            .SetColumns(a => a.ENDTIME == input.ENDTIME)
                            .SetColumns(a => a.BUSINESSSCOPE == input.BUSINESSSCOPE)
                            .SetColumns(a => a.SJPRODUCTS == input.SJPRODUCTS)
                            .SetColumns(a => a.PURCHASEAMOUNT == Convert.ToDouble(input.PURCHASEAMOUNT))
                            .SetColumns(a => a.OPPONENTAMOUNT == Convert.ToDouble(input.OPPONENTAMOUNT))
                            .SetColumns(a => a.BACKGROUND == input.BACKGROUND)
                            .SetColumns(a => a.DEVELOPMENTREASON == input.DEVELOPMENTREASON)
                            .SetColumns(a => a.PURCHASEDESCRIPTION == input.PURCHASEDESCRIPTION)
                            .SetColumns(a => a.PURCHASEDATA == input.PURCHASEDATA)
                            .SetColumns(a => a.STATE == state)
                            .SetColumns(a => a.CREATETIME == DateTime.Now)

                            .Where(a => a.ID == input.ID)
                            .ExecuteCommandAsync();

                        if (count == 0)
                        {
                            throw Oops.Oh("修改失败！");
                        }
                        _SjDb.Ado.CommitTran();
                        return "修改成功！";
                    }
                    catch (Exception e)
                    {
                        _SjDb.Ado.RollbackTran();
                        throw Oops.Oh($"异常：{e.Message}");
                    }
                }
            }
            else
            {
                throw Oops.Oh("状态码提交异常，驳回！");
            }
        }
        /// <summary>
        /// 业务员下拉框列表
        /// </summary>
        /// <returns></returns>
        [HttpPost("/Order/GetSalesmanList")]
        public async Task<List<SalesmanList>> GetSalesmanList()
        {
            return await _Dilon.Queryable<SysUserRole>()
                  .LeftJoin<SysUser>((r, u) => (r.UserId == u.Id))
                        .Where((r, u) => r.RoleId.ToString() == Salesman)


                       .Select((r, u) => new SalesmanList
                       {
                           USERID = u.Account,
                           USERNAME = u.RealName,

                       }).ToListAsync();
        }
        /// <summary>
        /// 业务员转让
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/Order/UpdateCustomerUser")]
        public async Task<string> UpdateCustomerUser(CustomerComplaintuser input)
        {


            //判断单据存在
            int cnt = await _SjDb.Queryable<FilingClient>()
                .Where(a => a.ID == input.ID)
                .Select(a => a.ID)
                .CountAsync();
            //业务员信息
            var userdata = await _Dilon.Queryable<SysUser>()
                .Where(a => a.Account == input.USERID)
      .Select(l => new SysUser
      {
          Account = l.Account,
          Phone = l.Phone,
          Email = l.Email,
          RealName = l.RealName
      }).FirstAsync();
            if (cnt == 0)
            {
                throw Oops.Oh("任务不存在，驳回！");
            }
            else
            {
                //提交
                try
                {
                    _SjDb.Ado.BeginTran();
                    int count = await _SjDb.Updateable<FilingClient>()
                        .SetColumns(a => a.BBR == userdata.RealName)
                        .SetColumns(a => a.BBRPHONE == userdata.Phone)
                        .SetColumns(a => a.BBREMAIL == userdata.Email)
                        .SetColumns(a => a.BBRID == userdata.Account)

                        .Where(a => a.ID == input.ID)
                        .ExecuteCommandAsync();

                    if (count == 0)
                    {
                        throw Oops.Oh("修改失败！");
                    }
                    _SjDb.Ado.CommitTran();
                    return "修改成功！";
                }
                catch (Exception e)
                {
                    _SjDb.Ado.RollbackTran();
                    throw Oops.Oh($"异常：{e.Message}");
                }
            }

        }


        /// <summary>
        /// 报备客户状态更改（定时任务）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/Order/UpdateComputerRoomState")]
        public async void UpdateComputerRoomState()
        {
            var output = _SjDb.Ado.SqlQuery<CustomerReportOutput>($@"  select * from( SELECT f.*,TRUNC(end_time) - TRUNC(SYSDATE) AS dayDiff
FROM FILING_CLIENT f where (STATE=1 OR STATE = 5)) where  dayDiff>=3
                            ").ToList();
            List<string> sxkhid = new List<string>();//状态需要改为即将失效的客户
            List<string> ysxkhid = new List<string>();//状态需要改为已失效的客户
            if (output.Count > 0)
            {
                for (int i = 0; i < output.Count; i++)
                {
                    if (output[i].dayDiff == 3 && output[i].STATE == 3)//当客户状态为3开发中，且当前日期离报备日期只差3天
                    {
                        sxkhid.Add(output[i].ID);
                        Sms.SendSms(output[i].BBRPHONE, "SMS_463375093", output[i].CUSTOMERNAME);
                    }
                    if (output[i].dayDiff == 0 && output[i].STATE == 5)//当客户状态为5即将失效，且当前日期等于报备日期
                    {
                        ysxkhid.Add(output[i].ID);
                    }
                }
            }
            //提交
            try
            {
                if (sxkhid.Count > 0)
                    _SjDb.Ado.BeginTran();
                if (sxkhid.Count > 0)
                {
                    await _SjDb.Updateable<FilingClient>()

                        .SetColumns(a => a.STATE == 5)
                        .Where(a => sxkhid.Contains(a.ID))
                        .ExecuteCommandAsync();
                }
                if (ysxkhid.Count > 0)
                {
                    await _SjDb.Updateable<FilingClient>()

                        .SetColumns(a => a.STATE == 6)
                        .Where(a => ysxkhid.Contains(a.ID))
                        .ExecuteCommandAsync();
                }

                _SjDb.Ado.CommitTran();
            }
            catch (Exception e)
            {
                _SjDb.Ado.RollbackTran();
                throw Oops.Oh($"异常：{e.Message}");
            }


        }

        /// <summary>
        /// OA审核报备客户状态更改
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/Order/UpdateSHComputerRoomState")]
        [AllowAnonymous]
        public async Task<string> UpdateSHComputerRoomState(CustomerSHInput input)
        {
            var type = 2;
            if (input.STATE == 0)
                type = 2;
            else
                type = 3;

            //提交
            try
            {
                _SjDb.Ado.BeginTran();
               //2审核不通过;3审核通过
                    await _SjDb.Updateable<FilingClient>()
                        .SetColumns(a => a.STATE == type)
                          .SetColumns(a => a.SHREMARKS == input.SHREMARKS)
                        .Where(a => a.TAXID == input.TAXID && a.PRODUCTSLINE == input.PRODUCTSLINE)
                        .ExecuteCommandAsync();
                _SjDb.Ado.CommitTran();
                return "修改成功！";
            }
            catch (Exception e)
            {
                _SjDb.Ado.RollbackTran();
                throw Oops.Oh($"异常：{e.Message}");
            }
        }
        /// <summary>
        ///  获取报备申诉列表-分页
        /// </summary>
        /// <returns></returns>
        [HttpPost("/Order/GetCustomerComplaintPagedList")]
        public async Task<SqlSugarPagedList<CUSTOMERCOMPLAINT>> GetCustomerComplaintPagedList(CustomerSSInput input)
        {
            // 角色信息
            var roles = await _sysUserRoleService.GetUserRoleList(_User.ID.ToLong());
            var LoginRole = roles.Select(u => new LoginRole
            {
                Name = u.Name,
                Code = u.Code,
                Id = u.Id.ToString(),
            }).ToList();
            int role = LoginRole.Where(u => u.Id.ToString() == "14478138094149").Count();//判断是否拥有业务员角色


            var output = await _SjDb.Queryable<CUSTOMERCOMPLAINT>()
                .Where(l => l.COMPLAINTSTATE == 0)//申诉未处理的数据
    .OrderBy(l => l.COMPLAINTTIME, OrderByType.Desc) //报备日期排序
    .Select(l => new CUSTOMERCOMPLAINT
    {
        ID = l.ID,
        TAXID = l.TAXID,
        PRODUCTSLINE = l.PRODUCTSLINE,
        COMPLAINTNUM = l.COMPLAINTNUM,
        COMPLAINTCONTENT = l.COMPLAINTCONTENT,
        CUSTOMERNAME = l.CUSTOMERNAME,
        COMPLAINTSTATE = l.COMPLAINTSTATE,
        COMPLAINTUSER = l.COMPLAINTUSER,
        COMPLAINTTIME = l.COMPLAINTTIME,
        COMPLAINTSHCONTENT = l.COMPLAINTSHCONTENT,


    }).ToPagedListAsync(input.Page, input.PageSize);
            return output;
        }
        /// <summary>
        /// 报备申诉添加
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/Order/AddCustomerComplaint")]
        public async Task<string> AddCustomerComplaint(CustomerComplaintInput input)
        {
            //判断单据存在
            int cnt = await _SjDb.Queryable<OrderCustomer>()
                .Where(a => a.ORDERID == input.COMPLAINTNUM && a.BUSINESSPERSON == _User.UserId)
                .Select(a => a.CID)
                .CountAsync();
            if (cnt == 0)
            {
                throw Oops.Oh("申诉失败，查不到此订单！");
            }
            else
            {

                var details = new CUSTOMERCOMPLAINT
                {
                    TAXID = input.TAXID,
                    PRODUCTSLINE = input.PRODUCTSLINE,
                    COMPLAINTNUM = input.COMPLAINTNUM,
                    COMPLAINTCONTENT = input.COMPLAINTDATA,
                    CUSTOMERNAME = input.CUSTOMERNAME,
                    COMPLAINTSTATE = 0,//申诉中
                    COMPLAINTTIME = DateTime.Now,
                    COMPLAINTUSER = _User.RealName
                };
                #region 插入事务
                try
                {
                    //开启事务
                    _SjDb.Ado.BeginTran();
                    int cnt1 = await _SjDb.Insertable<CUSTOMERCOMPLAINT>(details).ExecuteCommandAsync();

                    if (cnt1 == 0)
                    {
                        throw Oops.Oh($"新建任务失败！");
                    }
                    //提交事务
                    _SjDb.Ado.CommitTran();

                    return "插入成功";
                }
                catch (Exception e)
                {
                    //回滚事务
                    _SjDb.Ado.RollbackTran();
                    throw Oops.Oh($"异常：{e.Message}");
                }
                #endregion
            }

        }

        /// <summary>
        ///申诉结果更改
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/Order/UpdateCustomerComplaintState")]
        public async Task<string> UpdateCustomerComplaintState(CustomerComplaintSHInput input)
        {
            //判断单据存在
            int cnt = await _SjDb.Queryable<CustomerComplaintSHInput>()
                .Where(a => a.ID == input.ID)
                .Select(a => a.ID)
                .CountAsync();


            if (cnt == 0)
            {
                throw Oops.Oh("任务不存在，驳回！");
            }
            else
            {
                //提交
                try
                {
                    _SjDb.Ado.BeginTran();
                    await _SjDb.Updateable<CUSTOMERCOMPLAINT>()
                        .SetColumns(a => a.COMPLAINTSTATE == input.COMPLAINTSTATE)
                        .SetColumns(a => a.COMPLAINTSHCONTENT == input.COMPLAINTSHDATA)
                        .Where(a => a.ID == input.ID)
                        .ExecuteCommandAsync();
                    if (input.COMPLAINTSTATE == 1)//开发成功
                    {
                        await _SjDb.Updateable<FilingClient>()
                      .SetColumns(a => a.STATE == 4)
                      .Where(a => a.TAXID == input.TAXID && a.PRODUCTSLINE == input.PRODUCTSLINE)
                      .ExecuteCommandAsync();
                    }


                    _SjDb.Ado.CommitTran();
                    return "成功";
                }
                catch (Exception e)
                {
                    _SjDb.Ado.RollbackTran();
                    throw Oops.Oh($"异常：{e.Message}");
                }
            }

        }
    }

}